package guda.house.web.action.bill;

import guda.grape.autogen.common.page.BizResult;
import guda.grape.util.RequestUtil;
import guda.house.biz.InvoiceLogBiz;
import guda.house.biz.beans.vo.BillExtVO;
import guda.house.biz.beans.vo.BillExtXlsVO;
import guda.house.biz.beans.vo.JsonResult;
import guda.house.biz.enums.BillCatEnum;
import guda.house.biz.enums.BooleanEnum;
import guda.house.biz.form.InvoiceSearchForm;
import guda.house.biz.form.bill.BillDepositSearchForm;
import guda.house.biz.form.bill.InvoiceLogEditForm;
import guda.house.biz.form.bill.InvoiceLogForm;
import guda.house.biz.form.bill.InvoiceLogReverseForm;
import guda.house.biz.query.AccountEstateQuery;
import guda.house.biz.query.BillDepositQuery;
import guda.house.biz.query.InvoiceLogQuery;
import guda.house.biz.query.SuiteQuery;
import guda.house.biz.security.AppUtil;
import guda.house.biz.util.ErrorCode;
import guda.house.biz.util.ExportExcelUtil;
import guda.house.biz.util.PriceUtil;
import guda.house.dal.dao.BuildingDAO;
import guda.house.dal.dao.SuiteDAO;
import guda.house.dal.dao.UnitDAO;
import guda.house.dal.dao.VillageDAO;
import guda.house.dal.dataobject.*;
import guda.house.web.helper.ResponseHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by well on 15/11/16.
 */
@Controller
@RequestMapping(value = "bill/invoiceLog")
public class InvoiceLogAction {

    @Autowired
    private InvoiceLogBiz invoiceLogBiz;
    @Autowired
    private VillageDAO villageDAO;
    @Autowired
    private BuildingDAO buildingDAO;
    @Autowired
    private UnitDAO unitDAO;
    @Autowired
    private SuiteDAO suiteDAO;

    @RequestMapping(value = "list.htm", method = RequestMethod.GET)
    public String list(HttpServletRequest request, ModelMap modelMap,InvoiceSearchForm invoiceSearchForm) {
        int pageId = RequestUtil.getInt(request, "pageNo");
        int pageSize = RequestUtil.getInt(request, "pageSize");
        if(invoiceSearchForm.getVillageId() == null) {
            List<Long> villageIdList = AppUtil.getVillageIdList();
            if (villageIdList.size() > 0) {
                invoiceSearchForm.setVillageId(villageIdList.get(0));
            }
        }
        InvoiceLogQuery invoiceLogQuery = new InvoiceLogQuery();
        invoiceLogQuery.setPageNo(pageId);
        invoiceLogQuery.setPageSize(pageSize);
        invoiceLogQuery.setInvoiceSerial(invoiceSearchForm.getInvoiceSerial());
        invoiceLogQuery.setVillageId(invoiceSearchForm.getVillageId());
        modelMap.put("query", invoiceLogQuery);
        BizResult bizResult = invoiceLogBiz.list(invoiceLogQuery);
        if (bizResult.success) {
            modelMap.putAll(bizResult.data);
            return "bill/invoiceLog/list.vm";
        } else {
            return "redirect:/error.htm?code=" + bizResult.code;
        }
    }




    @RequestMapping(value = "/create.htm")
    public String create(HttpServletRequest request, ModelMap modelMap, InvoiceLogForm invoiceLogForm,
                         BindingResult result) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        invoiceLogForm.setGmtInvoice(format);
        BizResult bizResult = invoiceLogBiz.queryForCreate(invoiceLogForm);
        modelMap.putAll(bizResult.data);
        return "bill/invoiceLog/create.vm";
    }

    @RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
    public String edit(HttpServletRequest request, ModelMap modelMap, InvoiceLogEditForm invoiceLogEditForm,
                         BindingResult result) {
        BizResult bizResult = invoiceLogBiz.queryForEdit(invoiceLogEditForm);
        modelMap.putAll(bizResult.data);
        return "bill/invoiceLog/edit.vm";
    }

    @RequestMapping(value = "/doCreate.htm", method = RequestMethod.POST)
    public String doCreate(HttpServletRequest request, ModelMap modelMap, @Valid InvoiceLogForm invoiceLogForm,
                           BindingResult result) {
        if (result.hasErrors()) {
            BizResult bizResult3 = invoiceLogBiz.queryForCreate(invoiceLogForm);
            modelMap.putAll(bizResult3.data);
            return "bill/invoiceLog/create.vm";
        }
        BizResult bizResult = invoiceLogBiz.create(invoiceLogForm);
        if (bizResult.success) {
            return "redirect:/bill/invoiceLog/list.htm";
        } else {
            return "redirect:/error.htm?code=" + bizResult.code;
        }

    }


    @RequestMapping(value = "/doUpdate.htm", method = RequestMethod.POST)
    public String doUpdate(HttpServletRequest request, ModelMap modelMap, @Valid InvoiceLogEditForm invoiceLogEditForm,
                           BindingResult result) {
        if (result.hasErrors()) {
            BizResult bizResult = invoiceLogBiz.queryForEdit(invoiceLogEditForm);
            modelMap.putAll(bizResult.data);
            return "bill/invoiceLog/edit.vm";
        }
        BizResult bizResult = invoiceLogBiz.update(invoiceLogEditForm);
        if (bizResult.success) {
            return "redirect:/bill/invoiceLog/list.htm";
        } else {
            return "redirect:/error.htm?code=" + bizResult.code;
        }

    }

    @RequestMapping(value = "export.do", method = RequestMethod.GET)
    public void export(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap, InvoiceSearchForm invoiceSearchForm) {

        String filedisplay = null;
        try {
            filedisplay = URLEncoder.encode("发票记录.xls", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("application/x-download; charset=UTF-8");
        response.addHeader("Content-Disposition", "attachment; filename=" + filedisplay);

        InvoiceLogQuery invoiceLogQuery = new InvoiceLogQuery();
        invoiceLogQuery.setPageSize(10000);
        invoiceLogQuery.setInvoiceSerial(invoiceSearchForm.getInvoiceSerial());
        invoiceLogQuery.setVillageId(invoiceSearchForm.getVillageId());
        BizResult bizResult = invoiceLogBiz.list(invoiceLogQuery);
        List<InvoiceLogDO> invoiceLogDOList = (List<InvoiceLogDO>)bizResult.data.get("invoiceLogList");
        List<InvoiceLogXlsVO> invoiceLogXlsVOList = new ArrayList<InvoiceLogXlsVO>(invoiceLogDOList.size());
        for(InvoiceLogDO invoiceLogDO:invoiceLogDOList){
            InvoiceLogXlsVO invoiceLogXlsVO = new InvoiceLogXlsVO();
            invoiceLogXlsVO.setInvoiceSerial(invoiceLogDO.getInvoiceSerial());
            invoiceLogXlsVO.setInvoiceCat(invoiceLogDO.getInvoiceCat());
            invoiceLogXlsVO.setInvoiceNo(invoiceLogDO.getInvoiceNo());
            invoiceLogXlsVO.setMoney(PriceUtil.formatCNY(invoiceLogDO.getInvoiceMoney()));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            invoiceLogXlsVO.setTime(simpleDateFormat.format(invoiceLogDO.getGmtCreate()));
            invoiceLogXlsVO.setInvoiceType(invoiceLogDO.getInvoiceType());
            SuiteDO suiteById = suiteDAO.getSuiteById(invoiceLogDO.getSuiteId());
            UnitDO unitDO = unitDAO.getUnitById(suiteById.getUnitId());
            BuildingDO buildingById = buildingDAO.getBuildingById(unitDO.getBuildingId());
            VillageDO villageById = villageDAO.getVillageById(buildingById.getVillageId());
            invoiceLogXlsVO.setSuiteName(suiteById.getSuiteName());
            invoiceLogXlsVO.setBuildingName(buildingById.getBuildingName());
            invoiceLogXlsVO.setUnitName(unitDO.getUnitName());
            invoiceLogXlsVO.setVillageName(villageById.getVillageName());
            invoiceLogXlsVOList.add(invoiceLogXlsVO);
        }
        String[] headers = new String[]{"发票序号","小区","楼栋","单元","房号","开票金额","开票时间","发票号码","发票类型","开票类型"};
        String[] fields = new String[]{"invoiceSerial","villageName","buildingName","unitName","suiteName","money","time","invoiceNo","invoiceType","invoiceCat"};
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ExportExcelUtil.exportExcel("发票记录", headers, fields, invoiceLogXlsVOList, outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @RequestMapping(value = "/reverse.htm")
    public String reverse(HttpServletRequest request, ModelMap modelMap, InvoiceLogReverseForm invoiceLogReverseForm,
                         BindingResult result) {

        BizResult bizResult = invoiceLogBiz.queryForReverse(invoiceLogReverseForm.getLogId());
        modelMap.putAll(bizResult.data);
        return "bill/invoiceLog/reverse.vm";
    }


    @RequestMapping(value = "/doReverse.htm")
    public String doReverse(HttpServletRequest request, ModelMap modelMap, @Valid InvoiceLogReverseForm invoiceLogReverseForm,
                          BindingResult result) {
        if (result.hasErrors()) {
            BizResult bizResult = invoiceLogBiz.queryForReverse(invoiceLogReverseForm.getLogId());
            modelMap.putAll(bizResult.data);
            return "bill/invoiceLog/reverse.vm";
        }
        BizResult bizResult = invoiceLogBiz.reverse(invoiceLogReverseForm);
        modelMap.putAll(bizResult.data);
        return "bill/invoiceLog/reverseSuccess.vm";
    }





}
